import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Button, message, Slider, InputNumber, Space, Switch } from 'antd';
import { CloseOutlined, PlayCircleOutlined, PauseCircleOutlined } from '@ant-design/icons';
import { FloodByGraphic, PolyUtil } from '../../../../../../common/FloodAnalysis';
import ZoneApi from '../../../../../../../utils/apis/ZoneApi';
import './FloodAnalysisModal.less';
import normalFloodPointIcon from './images/内涝点.png';
import warningFloodPointIcon from './images/内涝点预警.png';

// 获取类型名称的辅助函数
const getTypeName = (type) => {
    const typeNames = {
        'riverbank': '河边低地',
        'school': '学校',
        'government': '政府机构',
        'hospital': '医院',
        'commercial': '商业区',
        'sports': '体育中心',
        'cultural': '文化场所',
        'transport': '交通枢纽',
        'industrial': '工业园区',
        'mountain': '山地'
    };
    return typeNames[type] || type;
};

// 更新内涝点信息框内容的函数
const updateFloodPointDescription = (pointData) => {
    if (pointData.entity) {
        pointData.entity.description = new Cesium.ConstantProperty(
            `<table class="cesium-infoBox-defaultTable">
                <tr><th colspan="2">内涝点信息</th></tr>
                <tr><td><strong>名称:</strong></td><td>${pointData.name}</td></tr>
                <tr><td><strong>类型:</strong></td><td>${getTypeName(pointData.type)}</td></tr>
                <tr><td><strong>高程:</strong></td><td>${pointData.height.toFixed(1)}m</td></tr>
                <tr><td><strong>警戒水位:</strong></td><td>${pointData.height.toFixed(1)}m</td></tr>
                <tr><td><strong>当前状态:</strong></td><td><span style="color: ${pointData.isFlooded ? 'red' : 'green'}">${pointData.isFlooded ? '预警' : '正常'}</span></td></tr>
                <tr><td><strong>地址:</strong></td><td>四川省南充市嘉陵区${pointData.name}</td></tr>
            </table>`
        );
    }
};

export default function FloodAnalysisModal({ visible, onClose }) {
    const cesiumContainerRef = useRef(null);
    const viewerRef = useRef(null);
    const floodByGraphicRef = useRef(null);

    const [isLoading, setIsLoading] = useState(true);
    const [waterLevel, setWaterLevel] = useState(50); // 水位高度
    const [floodSpeed, setFloodSpeed] = useState(2); // 淹没速度 (米/秒)
    const [currentFloodLevel, setCurrentFloodLevel] = useState(0); // 当前淹没高度
    const [isAnalyzing, setIsAnalyzing] = useState(false); // 是否正在分析
    const [hasArea, setHasArea] = useState(false); // 是否有分析区域
    const [minHeight, setMinHeight] = useState(0); // 最低高程
    const [maxHeight, setMaxHeight] = useState(100); // 最高高程
    const [renderMode, setRenderMode] = useState('unified'); // 渲染模式
    const [adminBoundary, setAdminBoundary] = useState(null); // 行政边界实体
    const [showAdminBoundary, setShowAdminBoundary] = useState(true); // 是否显示行政边界
    const [analysisPositions, setAnalysisPositions] = useState(null); // 分析区域坐标
    const [floodPoints, setFloodPoints] = useState([]); // 内涝点实体

    // 生成内涝点数据
    const generateFloodPoints = (boundaryPositions, viewer) => {
        if (!boundaryPositions || boundaryPositions.length === 0) return [];
        
        const Cesium = window.Cesium;
        const floodPointsData = [];
        
        // 使用嘉陵区真实地理坐标的内涝点配置
        // 基于嘉陵区行政边界，东南西北中全面分布
        // 嘉陵区大致范围：经度 105.75-106.05，纬度 30.70-30.95
        const pointConfigs = [
            // 东部江边区域（最容易受淹）- 经度更大，靠近嘉陵江
            {
                name: '嘉陵江东岸渔村',
                type: 'riverbank',
                longitude: 106.00, // 东边，靠近嘉陵江
                latitude: 30.70, // 最南边
                baseHeight: 170, // 河边最低地，最容易受淹
                heightVariation: 5
            },
            {
                name: '嘉陵江东岸码头',
                type: 'riverbank',
                longitude: 106.02, // 东边，靠近嘉陵江
                latitude: 30.72, // 南部
                baseHeight: 175, // 河边低地
                heightVariation: 8
            },
            {
                name: '嘉陵江东岸渡口',
                type: 'riverbank',
                longitude: 106.04, // 东边，靠近嘉陵江
                latitude: 30.74, // 中南部
                baseHeight: 172, // 河边低地
                heightVariation: 6
            },
            {
                name: '嘉陵江东岸沙洲',
                type: 'riverbank',
                longitude: 106.05, // 最东边，靠近嘉陵江
                latitude: 30.76, // 中部
                baseHeight: 168, // 河边最低地
                heightVariation: 4
            },
            {
                name: '嘉陵江边居民区',
                type: 'riverbank',
                longitude: 106.03, // 东边，靠近嘉陵江
                latitude: 30.78, // 中北部
                baseHeight: 180, // 河边低地
                heightVariation: 10
            },
            {
                name: '嘉陵江东岸工业区',
                type: 'industrial',
                longitude: 106.01, // 东边，靠近嘉陵江
                latitude: 30.80, // 北部
                baseHeight: 185, // 河边低地
                heightVariation: 8
            },
            
            // 南部区域 - 精简版（纬度30.55-30.65）
            {
                name: '嘉陵区南部医院',
                type: 'hospital',
                longitude: 105.90, // 中部
                latitude: 30.55, // 最南边
                baseHeight: 200,
                heightVariation: 12
            },
            {
                name: '嘉陵区南部学校',
                type: 'school',
                longitude: 105.94, // 中东部
                latitude: 30.57, // 南边
                baseHeight: 195,
                heightVariation: 10
            },
            {
                name: '嘉陵区南部工业园',
                type: 'industrial',
                longitude: 105.98, // 东部
                latitude: 30.54, // 最南边
                baseHeight: 195,
                heightVariation: 10
            },
            {
                name: '嘉陵区南部商业区',
                type: 'commercial',
                longitude: 106.02, // 最东边
                latitude: 30.59, // 南边
                baseHeight: 190,
                heightVariation: 8
            },
            {
                name: '嘉陵区南部居民区',
                type: 'riverbank',
                longitude: 106.06, // 最东边
                latitude: 30.56, // 南边
                baseHeight: 185,
                heightVariation: 8
            },
            {
                name: '嘉陵区南部交通站',
                type: 'transport',
                longitude: 105.92, // 中东部
                latitude: 30.58, // 南边
                baseHeight: 205,
                heightVariation: 12
            },
            {
                name: '嘉陵区南部工业区',
                type: 'industrial',
                longitude: 105.96, // 东部
                latitude: 30.55, // 最南边
                baseHeight: 200,
                heightVariation: 10
            },
            {
                name: '嘉陵区南部商业街',
                type: 'commercial',
                longitude: 106.00, // 最东边
                latitude: 30.61, // 南边
                baseHeight: 185,
                heightVariation: 8
            },
            {
                name: '嘉陵区南部文化中心',
                type: 'cultural',
                longitude: 106.04, // 最东边
                latitude: 30.57, // 南边
                baseHeight: 202,
                heightVariation: 12
            },
            {
                name: '嘉陵区南部体育场',
                type: 'sports',
                longitude: 105.91, // 中东部
                latitude: 30.54, // 最南边
                baseHeight: 198,
                heightVariation: 10
            },
            {
                name: '嘉陵区南部公园',
                type: 'cultural',
                longitude: 105.95, // 东部
                latitude: 30.60, // 南边
                baseHeight: 195,
                heightVariation: 10
            },
            {
                name: '嘉陵区南部市场',
                type: 'commercial',
                longitude: 105.99, // 最东边
                latitude: 30.56, // 南边
                baseHeight: 188,
                heightVariation: 8
            },
            {
                name: '嘉陵区南部社区',
                type: 'riverbank',
                longitude: 106.03, // 最东边
                latitude: 30.58, // 南边
                baseHeight: 190,
                heightVariation: 8
            },
            
            // 中部区域
            {
                name: '嘉陵区文化广场',
                type: 'cultural',
                longitude: 105.88, // 中西部
                latitude: 30.75, // 中部
                baseHeight: 210,
                heightVariation: 10
            },
            {
                name: '嘉陵区第一中学',
                type: 'school',
                longitude: 105.92, // 西部
                latitude: 30.78, // 中北部
                baseHeight: 220,
                heightVariation: 15
            },
            
            // 西部区域 - 经度更小，不超出嘉陵区边界
            {
                name: '嘉陵区政府',
                type: 'government',
                longitude: 105.78, // 西部
                latitude: 30.84, // 北部
                baseHeight: 240,
                heightVariation: 10
            },
            
            // 北部区域 - 减少北边点位
            {
                name: '嘉陵区体育中心',
                type: 'sports',
                longitude: 105.85, // 中西部
                latitude: 30.87, // 北部
                baseHeight: 260,
                heightVariation: 15
            }
        ];
        
        for (let i = 0; i < pointConfigs.length; i++) {
            const config = pointConfigs[i];
            
            // 使用真实经纬度坐标
            const lon = config.longitude;
            const lat = config.latitude;
            
            // 创建位置
            const position = Cesium.Cartesian3.fromDegrees(lon, lat);
            
            // 计算高程，基于配置和随机变化
            let baseHeight = config.baseHeight + (Math.random() - 0.5) * config.heightVariation;
            
            // 根据类型调整高程
            switch (config.type) {
                case 'riverbank':
                    // 河边低地，容易被淹没
                    baseHeight = Math.max(175, Math.min(195, baseHeight));
                    break;
                case 'mountain':
                    // 山地，不容易被淹没
                    baseHeight = Math.max(300, Math.min(350, baseHeight));
                    break;
                case 'industrial':
                    // 工业园区，中等高度
                    baseHeight = Math.max(270, Math.min(290, baseHeight));
                    break;
                case 'sports':
                    // 体育中心，较高位置
                    baseHeight = Math.max(250, Math.min(270, baseHeight));
                    break;
                default:
                    // 其他类型，保持原有范围
                    baseHeight = Math.max(180, Math.min(250, baseHeight));
            }
            
            console.log(`内涝点 ${config.name} (${config.type}): 高程=${baseHeight.toFixed(1)}m, 位置=(${lon.toFixed(6)}, ${lat.toFixed(6)}), 经度=${lon.toFixed(3)}°E`);
            
            floodPointsData.push({
                id: `flood_point_${i}`,
                name: config.name,
                type: config.type,
                position: position,
                height: baseHeight,
                isFlooded: false,
                entity: null
            });
        }
        
        return floodPointsData;
    };



    const initializeCesium = useCallback(() => {
        try {
            setIsLoading(true);
            console.log('开始初始化Cesium...');

            // 检查Cesium是否已加载
            if (!window.Cesium) {
                console.error('Cesium未加载');
                message.error('Cesium未加载完成，请稍后重试');
                setIsLoading(false);
                return;
            }

            const Cesium = window.Cesium;
            console.log('Cesium已加载，版本:', Cesium.VERSION);

            // 设置Cesium资源路径
            window.CESIUM_BASE_URL = process.env.PUBLIC_URL + '/cdn/Cesium/';

            // 设置Cesium Ion Token
            Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMmZjMmYyZC1lZTkzLTQzYjctYmE2NS01NTQ0NzQyMWZhNDMiLCJpZCI6MTA2NjEsImlhdCI6MTYwNjI4NjY2MH0.PN1-x4vXpC68czogub9X0UDA3GaGE-31PZVbrRyI7CQ';

            console.log('创建Cesium Viewer...');
            // 初始化Cesium Viewer
            const viewer = new Cesium.Viewer(cesiumContainerRef.current, {
                selectionIndicator: false,
                animation: false,
                homeButton: false,
                geocoder: false,
                baseLayerPicker: false,
                timeline: false,
                fullscreenButton: false,
                scene3DOnly: true,
                infoBox: true,
                sceneModePicker: false,
                navigationHelpButton: false,
                terrainProvider: new Cesium.CesiumTerrainProvider({
                    url: Cesium.IonResource.fromAssetId(1)
                }),
                skyAtmosphere: false,
                contextOptions: {
                    webgl: {
                        alpha: true,
                    },
                },
            });

            console.log('Cesium Viewer创建成功');

            // 配置场景
            viewer.scene.globe.terrainExaggeration = 1;
            viewer.scene.undergroundMode = false;
            viewer.scene.fxaa = true;
            viewer.scene.postProcessStages.fxaa.enabled = true;
            viewer._cesiumWidget._creditContainer.style.display = "none";
            viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString("#041320");
            viewer.scene.backgroundcolor = Cesium.Color.fromCssColorString("#041320");
            viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
            viewer.scene.globe.depthTestAgainstTerrain = true;

            console.log('场景配置完成');

            viewerRef.current = viewer;

            // 创建FloodByGraphic实例
            const floodByGraphic = new FloodByGraphic(viewer, {
                style: {
                    color: "#007be6",
                    opacity: 0.6,
                    outline: true,
                    renderMode: renderMode
                }
            });

            // 设置事件监听器
            floodByGraphic.on('start', (e) => {
                console.log('开始淹没分析', e);
                setIsAnalyzing(true);
                message.info('开始淹没分析');
            });

            floodByGraphic.on('change', (e) => {
                console.log('淹没高度变化', e);
                console.log('当前FloodByGraphic状态:', {
                    height: floodByGraphicRef.current?.height,
                    isAnalyzing: floodByGraphicRef.current?.isStart,
                    isActive: floodByGraphicRef.current?.isActive,
                    hasPositions: !!floodByGraphicRef.current?.positions,
                    hasElevationGrid: !!floodByGraphicRef.current?.elevationGrid
                });
                
                // 更新当前水位状态
                setCurrentFloodLevel(e.height);
                
                // 更新内涝点图标 - 使用更精确的淹没判断
                const Cesium = window.Cesium;
                setFloodPoints(prevPoints => {
                    const updatedPoints = prevPoints.map(pointData => {
                        // 添加调试信息
                        const isFlooded = pointData.height <= e.height;
                        console.log(`内涝点 ${pointData.name}: 高程=${pointData.height.toFixed(1)}m, 当前水位=${e.height.toFixed(1)}m, 是否淹没=${isFlooded}`);
                        
                        if (pointData.entity) {
                            let statusChanged = false;
                            
                            if (isFlooded && !pointData.isFlooded) {
                                // 如果内涝点高程低于当前水位，变为预警图标
                                pointData.entity.billboard.image = warningFloodPointIcon;
                                pointData.isFlooded = true;
                                statusChanged = true;
                                console.log(`内涝点 ${pointData.name} 已被淹没！`);
                            } else if (!isFlooded && pointData.isFlooded) {
                                // 如果内涝点高程高于当前水位，恢复为正常图标
                                pointData.entity.billboard.image = normalFloodPointIcon;
                                pointData.isFlooded = false;
                                statusChanged = true;
                                console.log(`内涝点 ${pointData.name} 已脱离淹没区域`);
                            }
                            
                            // 如果状态改变，更新信息框内容
                            if (statusChanged) {
                                updateFloodPointDescription(pointData);
                            }
                        }
                        return pointData;
                    });
                    return updatedPoints;
                });
                
                // 强制场景重新渲染，确保淹没效果实时显示
                if (viewerRef.current) {
                    viewerRef.current.scene.requestRender();
                }
                
                console.log('水位已更新为:', e.height);
            });

            floodByGraphic.on('end', (e) => {
                console.log('淹没分析结束', e);
                setIsAnalyzing(false);
                message.success('淹没分析完成');
            });

                        floodByGraphicRef.current = floodByGraphic;

            // 加载嘉陵区边界并设置为分析区域
            const loadJialingBoundary = async (viewer) => {
                try {
                    console.log('开始加载嘉陵区边界...');
                    const Cesium = window.Cesium;
                    
                    // 调用ZoneApi获取行政区域数据
                    const geoJsonData = await ZoneApi.children();
                    console.log('获取到行政区域数据:', geoJsonData);

                    if (!geoJsonData || !geoJsonData.features || geoJsonData.features.length === 0) {
                        console.warn('未获取到行政区域数据');
                        message.error('未获取到嘉陵区边界数据');
                        setIsLoading(false);
                        return;
                    }

                    // 收集所有边界坐标用于计算边界框
                    const allPositions = [];
                    const boundaryEntities = [];
                    let jialingPositions = []; // 存储嘉陵区的坐标

                    // 遍历所有行政区域并添加到地图
                    geoJsonData.features.forEach((feature, index) => {
                        if (feature.geometry && feature.geometry.type === 'MultiPolygon') {
                            const coordinates = feature.geometry.coordinates;
                            const properties = feature.properties || {};
                            
                            // 为每个多边形创建实体
                            coordinates.forEach((polygonCoords, polygonIndex) => {
                                const positions = [];
                                
                                // 转换坐标格式
                                polygonCoords[0].forEach(coord => {
                                    const position = Cesium.Cartesian3.fromDegrees(coord[0], coord[1]);
                                    positions.push(position);
                                    allPositions.push(position);
                                });

                                // 如果是嘉陵区，保存坐标用于分析
                                if (properties.name === '嘉陵区' || properties.name?.includes('嘉陵')) {
                                    jialingPositions = positions;
                                    console.log('找到嘉陵区边界，坐标点数量:', positions.length);
                                    
                                    // 计算嘉陵区的实际边界范围
                                    let minLon = Infinity, maxLon = -Infinity;
                                    let minLat = Infinity, maxLat = -Infinity;
                                    
                                    positions.forEach(pos => {
                                        const cartographic = Cesium.Cartographic.fromCartesian(pos);
                                        const lon = Cesium.Math.toDegrees(cartographic.longitude);
                                        const lat = Cesium.Math.toDegrees(cartographic.latitude);
                                        
                                        minLon = Math.min(minLon, lon);
                                        maxLon = Math.max(maxLon, lon);
                                        minLat = Math.min(minLat, lat);
                                        maxLat = Math.max(maxLat, lat);
                                    });
                                    
                                    console.log('嘉陵区实际边界范围:', {
                                        longitude: `${minLon.toFixed(6)} - ${maxLon.toFixed(6)}`,
                                        latitude: `${minLat.toFixed(6)} - ${maxLat.toFixed(6)}`,
                                        minLon, maxLon, minLat, maxLat
                                    });
                                }

                                // 计算标签位置（使用第一个坐标点，设置相对高度）
                                const labelPosition = Cesium.Cartesian3.fromDegrees(
                                    polygonCoords[0][0][0], 
                                    polygonCoords[0][0][1], 
                                    100 // 设置足够的高度，确保在地形之上
                                );

                                // 创建行政边界实体 - 嘉陵区使用更明显的样式
                                const isJialing = properties.name === '嘉陵区' || properties.name?.includes('嘉陵');
                                const boundaryEntity = viewer.entities.add({
                                    name: `行政边界_${properties.name || index}_${polygonIndex}`,
                                    polygon: {
                                        hierarchy: positions,
                                        material: Cesium.Color.TRANSPARENT, // 所有区域都透明，无填充色
                                        outline: true,
                                        outlineColor: isJialing ? Cesium.Color.CYAN : Cesium.Color.RED,
                                        outlineWidth: isJialing ? 12 : 8, // 嘉陵区边界更粗
                                        height: 0,
                                        extrudedHeight: 0, // 移除高度，只保留边界线
                                        perPositionHeight: false,
                                        classificationType: Cesium.ClassificationType.BOTH,
                                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                                    },
                                    label: {
                                        text: properties.name || `区域${index + 1}`,
                                        font: isJialing ? '24px sans-serif' : '18px sans-serif', // 嘉陵区字体更大
                                        fillColor: isJialing ? Cesium.Color.CYAN : Cesium.Color.RED,
                                        outlineColor: Cesium.Color.WHITE,
                                        outlineWidth: isJialing ? 6 : 4, // 嘉陵区轮廓更粗
                                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                                        pixelOffset: new Cesium.Cartesian2(0, -10),
                                        position: labelPosition,
                                        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
                                    }
                                });

                                // 如果是嘉陵区，添加额外的发光边界线
                                if (isJialing) {
                                    const glowLineEntity = viewer.entities.add({
                                        name: `嘉陵区发光边界_${polygonIndex}`,
                                        polyline: {
                                            positions: positions,
                                            width: 8,
                                            material: Cesium.Color.CYAN,
                                            clampToGround: true,
                                            zIndex: 1000
                                        }
                                    });
                                    boundaryEntities.push(glowLineEntity);
                                }

                                boundaryEntities.push(boundaryEntity);
                            });
                        }
                    });

                    // 保存边界实体引用
                    setAdminBoundary(boundaryEntities);
                    
                    console.log(`成功创建了 ${boundaryEntities.length} 个行政边界实体`);

                    // 计算行政区域的边界框并调整视角
                    if (allPositions.length > 0) {
                        try {
                            // 创建边界框
                            const boundingSphere = Cesium.BoundingSphere.fromPoints(allPositions);
                            
                            // 调整视角以显示完整的行政区域
                            viewer.camera.flyToBoundingSphere(boundingSphere, {
                                duration: 2.0, // 飞行时间2秒
                                offset: new Cesium.HeadingPitchRange(
                                    0, // heading
                                    Cesium.Math.toRadians(-45), // pitch
                                    boundingSphere.radius * 2.5 // 距离，稍微放大一点以便看到完整区域
                                )
                            });

                            console.log('视角已调整到行政区域');
                        } catch (flyError) {
                            console.warn('调整视角失败，使用默认视角:', flyError);
                            // 如果飞行失败，使用简单的setView
                            const center = Cesium.BoundingSphere.fromPoints(allPositions).center;
                            viewer.camera.setView({
                                destination: center,
                                orientation: {
                                    heading: Cesium.Math.toRadians(0),
                                    pitch: Cesium.Math.toRadians(-45),
                                    roll: 0.0
                                }
                            });
                        }
                    }

                    // 如果找到了嘉陵区边界，计算高程信息并设置为分析区域
                    if (jialingPositions.length > 0) {
                        console.log('开始计算嘉陵区高程信息...');
                        message.loading('正在计算嘉陵区高程信息...', 0);
                        
                        try {
                            const result = await PolyUtil.interPolygonByDepth({
                                scene: viewer.scene,
                                positions: jialingPositions
                            });

                            message.destroy();

                            setMinHeight(result.minHeight);
                            setMaxHeight(result.maxHeight);
                            setWaterLevel(result.avgHeight || result.minHeight + 10);
                            setAnalysisPositions(jialingPositions);
                            setHasArea(true);

                            console.log('嘉陵区高程信息:', result);
                            message.success(`嘉陵区边界已加载！高程范围: ${result.minHeight.toFixed(2)}m ~ ${result.maxHeight.toFixed(2)}m`);

                            // 设置FloodByGraphic的参数
                            if (floodByGraphicRef.current) {
                                await floodByGraphicRef.current.setOptions({
                                    positions: jialingPositions,
                                    minHeight: result.minHeight,
                                    maxHeight: result.maxHeight,
                                    speed: floodSpeed,
                                    style: {
                                        color: "#007be6",
                                        opacity: 0.6,
                                        outline: true,
                                        renderMode: renderMode
                                    }
                                });
                                console.log('FloodByGraphic参数设置完成');
                            } else {
                                console.warn('FloodByGraphic实例未准备好，跳过参数设置');
                            }

                            // 生成并创建内涝点
                            const floodPointsData = generateFloodPoints(jialingPositions, viewer);
                            const floodPointEntities = [];
                            
                            floodPointsData.forEach((pointData, index) => {
                                // 输出内涝点信息
                                console.log(`创建内涝点: ${pointData.name}, 高程: ${pointData.height.toFixed(1)}m`);
                                
                                // 创建内涝点实体
                                const pointEntity = viewer.entities.add({
                                    name: pointData.name,
                                    position: pointData.position,
                                    billboard: {
                                        image: normalFloodPointIcon, // 使用正常状态的内涝点图标
                                        width: 32,
                                        height: 32,
                                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                                        scale: 1.0
                                    },
                                    label: {
                                        text: pointData.name,
                                        font: '12px sans-serif',
                                        fillColor: Cesium.Color.WHITE,
                                        outlineColor: Cesium.Color.BLACK,
                                        outlineWidth: 1,
                                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                                        pixelOffset: new Cesium.Cartesian2(0, -40),
                                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                                        show: false // 默认不显示标签，鼠标悬停时显示
                                    }
                                });

                                // 创建包含实体的内涝点数据
                                const pointDataWithEntity = {
                                    ...pointData,
                                    entity: pointEntity
                                };

                                // 添加点击事件和属性信息
                                updateFloodPointDescription(pointDataWithEntity);

                                // 验证实体是否正确创建
                                console.log(`内涝点 ${pointData.name} 实体创建完成:`, {
                                    hasEntity: !!pointDataWithEntity.entity,
                                    hasDescription: !!pointDataWithEntity.entity.description,
                                    position: pointDataWithEntity.position
                                });

                                floodPointEntities.push(pointDataWithEntity);
                            });

                            setFloodPoints(floodPointEntities);
                            console.log(`成功创建了 ${floodPointEntities.length} 个内涝点`);

                        } catch (elevationError) {
                            message.destroy();
                            console.error('计算嘉陵区高程信息失败:', elevationError);
                            message.error('计算嘉陵区高程信息失败，请重试');
                        }
                    } else {
                        console.warn('未找到嘉陵区边界');
                        message.warning('未找到嘉陵区边界数据');
                    }

                    setIsLoading(false);
                    console.log('嘉陵区边界加载完成');

                } catch (error) {
                    console.error('加载嘉陵区边界失败:', error);
                    message.error(`加载嘉陵区边界失败: ${error.message}`);
                    setIsLoading(false);
                }
            };

            loadJialingBoundary(viewer);

        } catch (error) {
            console.error('初始化Cesium失败:', error);
            message.error(`初始化3D地图失败: ${error.message}`);
            setIsLoading(false);
        }
    }, [renderMode, floodSpeed]);

    useEffect(() => {
        if (visible) {
            // 延迟初始化，等待DOM完全渲染
            const timer = setTimeout(() => {
                console.log('检查容器元素:', cesiumContainerRef.current);
                if (cesiumContainerRef.current) {
                    initializeCesium();
                } else {
                    console.error('容器元素仍然为null，请检查DOM结构');
                    message.error('容器元素未准备好，请重试');
                    setIsLoading(false);
                }
            }, 100); // 延迟100ms

            return () => {
                clearTimeout(timer);
                if (viewerRef.current) {
                    viewerRef.current.destroy();
                }
            };
        }
    }, [visible, initializeCesium]);

    const handleModalClose = () => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.destroy();
            floodByGraphicRef.current = null;
        }

        if (viewerRef.current) {
            viewerRef.current.destroy();
            viewerRef.current = null;
        }

        // 重置所有状态
        setIsAnalyzing(false);
        setHasArea(false);
        setCurrentFloodLevel(0);
        setAnalysisPositions(null);

        onClose();
    };

    // 开始淹没分析
    const startAnalysis = async () => {
        if (!floodByGraphicRef.current || !hasArea) {
            message.warning('嘉陵区边界未加载完成');
            return;
        }

        try {
            console.log('开始淹没分析，重新计算内涝点高程...');
            
            // 重新计算内涝点的真实海拔高度
            const Cesium = window.Cesium;
            const updatedFloodPoints = [];
            
            for (let i = 0; i < floodPoints.length; i++) {
                const pointData = floodPoints[i];
                const position = pointData.position;
                
                try {
                    // 获取该位置的真实地形高程
                    const cartographic = Cesium.Cartographic.fromCartesian(position);
                    const terrainHeight = await Cesium.sampleTerrainMostDetailed(viewerRef.current.terrainProvider, [cartographic]);
                    
                    if (terrainHeight && terrainHeight.length > 0) {
                        const realHeight = terrainHeight[0].height;
                        console.log(`内涝点 ${pointData.name} 真实高程: ${realHeight.toFixed(1)}m (之前估算: ${pointData.height.toFixed(1)}m)`);
                        
                        // 更新内涝点的高程
                        pointData.height = realHeight;
                        pointData.isFlooded = false; // 重置淹没状态
                        
                        // 重置图标为正常状态
                        if (pointData.entity) {
                            pointData.entity.billboard.image = normalFloodPointIcon;
                            // 更新信息框内容
                            updateFloodPointDescription(pointData);
                        }
                    } else {
                        console.warn(`无法获取内涝点 ${pointData.name} 的真实高程，使用估算值`);
                    }
                } catch (error) {
                    console.warn(`获取内涝点 ${pointData.name} 高程失败:`, error);
                }
                
                updatedFloodPoints.push(pointData);
            }
            
            // 更新内涝点状态
            setFloodPoints(updatedFloodPoints);
            
            // 更新FloodByGraphic参数
            await floodByGraphicRef.current.setOptions({
                minHeight: minHeight,
                maxHeight: waterLevel,
                speed: floodSpeed
            });

            console.log('开始淹没分析...');
            floodByGraphicRef.current.start();
            
        } catch (error) {
            console.error('开始分析失败:', error);
            message.error('开始分析失败，请重试');
        }
    };

    // 停止淹没分析
    const stopAnalysis = () => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.stop();
        }
    };

    // 清除分析结果
    const clearAnalysis = () => {
        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.clear();
        }
        setCurrentFloodLevel(minHeight);
        setIsAnalyzing(false);
        
        // 重置内涝点图标
        const Cesium = window.Cesium;
        setFloodPoints(prevPoints => {
            prevPoints.forEach((pointData) => {
                if (pointData.entity) {
                    pointData.entity.billboard.image = normalFloodPointIcon;
                    pointData.isFlooded = false;
                }
            });
            return prevPoints;
        });
        
        message.info('已清除分析结果');
    };

    // 手动设置水位高度
    const onHeightChange = (value) => {
        console.log('onHeightChange被调用，新值:', value);
        
        if (floodByGraphicRef.current) {
            console.log('手动拖动slider:', {
                value: value,
                currentHeight: floodByGraphicRef.current.height,
                isAnalyzing: isAnalyzing,
                hasPositions: !!floodByGraphicRef.current.positions,
                hasElevationGrid: !!floodByGraphicRef.current.elevationGrid
            });
            
            // 直接设置高度
            floodByGraphicRef.current.height = value;
            setCurrentFloodLevel(value);
            
            // 更新内涝点图标 - 使用更精确的淹没判断
            const Cesium = window.Cesium;
            setFloodPoints(prevPoints => {
                console.log('开始更新内涝点状态，当前水位:', value);
                const updatedPoints = prevPoints.map(pointData => {
                    // 添加调试信息
                    const isFlooded = pointData.height <= value;
                    console.log(`检查内涝点 ${pointData.name}: 高程=${pointData.height.toFixed(1)}m, 当前水位=${value.toFixed(1)}m, 是否淹没=${isFlooded}`);
                    
                    if (pointData.entity) {
                        let statusChanged = false;
                        
                        if (isFlooded && !pointData.isFlooded) {
                            // 如果内涝点高程低于当前水位，变为预警图标
                            pointData.entity.billboard.image = warningFloodPointIcon;
                            pointData.isFlooded = true;
                            statusChanged = true;
                            console.log(`内涝点 ${pointData.name} 已被淹没！`);
                        } else if (!isFlooded && pointData.isFlooded) {
                            // 如果内涝点高程高于当前水位，恢复为正常图标
                            pointData.entity.billboard.image = normalFloodPointIcon;
                            pointData.isFlooded = false;
                            statusChanged = true;
                            console.log(`内涝点 ${pointData.name} 已脱离淹没区域`);
                        }
                        
                        // 如果状态改变，更新信息框内容
                        if (statusChanged) {
                            updateFloodPointDescription(pointData);
                        }
                    }
                    return pointData;
                });
                console.log('内涝点状态更新完成');
                return updatedPoints;
            });
            
            // 强制场景重新渲染，确保手动拖动时也能看到效果
            if (viewerRef.current) {
                viewerRef.current.scene.requestRender();
            }
            
            console.log('手动设置水位完成:', value);
        } else {
            console.warn('floodByGraphicRef.current不存在，无法更新水位');
        }
    };

    // 渲染模式改变
    const onRenderModeChange = (checked) => {
        const newMode = checked ? 'unified' : 'grid';
        setRenderMode(newMode);

        if (floodByGraphicRef.current) {
            floodByGraphicRef.current.options.style.renderMode = newMode;
        }
    };

    // 显示/隐藏行政边界
    const onAdminBoundaryChange = (checked) => {
        setShowAdminBoundary(checked);
        
        if (adminBoundary && Array.isArray(adminBoundary)) {
            adminBoundary.forEach(entity => {
                if (entity) {
                    entity.show = checked;
                }
            });
        }
    };

    return (
        <Modal
            className='modal-full-screen'
            title="嘉陵区洪水淹没分析"
            open={visible}
            onCancel={handleModalClose}
            width="90%"
            height="90%"
            style={{ top: 20 }}
            footer={null}
            destroyOnClose
        >
            <div style={{ height: '100%', position: 'relative' }}>
                {/* 3D场景容器 */}
                <div
                    ref={cesiumContainerRef}
                    style={{
                        width: '100%',
                        height: '100%',
                        background: '#041320'
                    }}
                />

                {/* 控制面板 */}
                <div
                    style={{
                        position: 'absolute',
                        top: 20,
                        left: 20,
                        bottom: 20,
                        background: '#000',
                        padding: '15px',
                        borderRadius: '8px',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
                        minWidth: '300px',
                        maxHeight: 'calc(90vh - 60px)',
                        overflowY: 'auto'
                    }}
                >
                    <h3 style={{ margin: '0 0 15px 0', color: '#1890ff' }}>控制面板</h3>

                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                        {/* 基础操作 */}
                        {/* <div>
                            <h4>基础操作</h4>
                            <Space>
                                <Button
                                    onClick={clearAnalysis}
                                    disabled={!viewerRef.current}
                                >
                                    清除分析
                                </Button>
                            </Space>
                        </div> */}

                        {/* 参数设置 */}
                        <div>
                            <h4>参数设置</h4>
                            <Space direction="vertical" style={{ width: '100%' }}>
                                <div>
                                    <label>最低高程 (m):</label>
                                    <InputNumber
                                        value={minHeight}
                                        onChange={setMinHeight}
                                        style={{ width: '100%' }}
                                        step={0.1}
                                        precision={1}
                                    />
                                </div>
                                <div>
                                    <label>目标水位 (m):</label>
                                    <InputNumber
                                        value={waterLevel}
                                        onChange={setWaterLevel}
                                        style={{ width: '100%' }}
                                        step={0.1}
                                        precision={1}
                                    />
                                </div>
                                <div>
                                    <label>淹没速度 (m/s):</label>
                                    <InputNumber
                                        value={floodSpeed}
                                        onChange={setFloodSpeed}
                                        style={{ width: '100%' }}
                                        step={0.1}
                                        precision={1}
                                        min={0.1}
                                        max={10}
                                    />
                                </div>
                                {/* <div>
                                    <label>渲染模式:</label>
                                    <Switch
                                        checked={renderMode === 'unified'}
                                        onChange={onRenderModeChange}
                                        checkedChildren="统一"
                                        unCheckedChildren="网格"
                                    />
                                </div>
                                <div>
                                    <label>显示行政边界:</label>
                                    <Switch
                                        checked={showAdminBoundary}
                                        onChange={onAdminBoundaryChange}
                                        checkedChildren="显示"
                                        unCheckedChildren="隐藏"
                                    />
                                </div> */}
                            </Space>
                        </div>

                        {/* 分析控制 */}
                        <div>
                            <h4>分析控制</h4>
                            <Space>
                                <Button
                                    type="primary"
                                    onClick={startAnalysis}
                                    disabled={!hasArea || isAnalyzing}
                                    icon={<PlayCircleOutlined />}
                                >
                                    开始分析
                                </Button>
                                <Button
                                    onClick={stopAnalysis}
                                    disabled={!isAnalyzing}
                                    icon={<PauseCircleOutlined />}
                                >
                                    停止分析
                                </Button>
                            </Space>
                        </div>

                        {/* 实时水位调节 */}
                        {hasArea && (
                            <div>
                                <h4>实时水位调节</h4>
                                <div>
                                    <label>当前水位: {currentFloodLevel.toFixed(1)}m</label>
                                    <Slider
                                        min={minHeight}
                                        max={Math.max(waterLevel, maxHeight)}
                                        value={currentFloodLevel}
                                        onChange={onHeightChange}
                                        step={0.1}
                                        tooltip={{ formatter: (value) => `${value.toFixed(1)}m` }}
                                    />
                                </div>
                            </div>
                        )}

                        {/* 状态信息 */}
                        <div>
                            <h4>状态信息</h4>
                            <div style={{ fontSize: '12px', color: '#666' }}>
                                <div>场景状态: {viewerRef.current ? '已初始化' : '初始化中...'}</div>
                                <div>嘉陵区边界: {hasArea ? '已加载' : '加载中...'}</div>
                                <div>行政边界: {showAdminBoundary ? '已显示' : '已隐藏'}</div>
                                <div>分析状态: {isAnalyzing ? '进行中' : '已停止'}</div>
                                <div>当前水位: {currentFloodLevel.toFixed(1)}m</div>
                                <div>高程范围: {minHeight.toFixed(1)}m ~ {maxHeight.toFixed(1)}m</div>
                                <div>内涝点数量: {floodPoints.length}个</div>
                                <div>已淹没点: {floodPoints.filter(p => p.isFlooded).length}个</div>
                            </div>
                        </div>
                    </Space>
                </div>

                {/* 操作提示 */}
                <div
                    style={{
                        position: 'absolute',
                        bottom: 20,
                        left: 20,
                        background: 'rgba(0,0,0,0.7)',
                        color: 'white',
                        padding: '10px',
                        borderRadius: '4px',
                        fontSize: '12px'
                    }}
                >
                    <div>操作提示:</div>
                    <div>• 嘉陵区边界已自动加载为分析区域</div>
                    <div>• 嘉陵区边界使用青色粗线显示，更加醒目</div>
                    <div>• 内涝点图标：正常状态为蓝色，预警状态为红色</div>
                    <div>• 设置参数后点击"开始分析"</div>
                    <div>• 可以实时调节水位滑块观看效果</div>
                    <div>• 点击"清除分析"重置水位</div>
                </div>
            </div>
        </Modal>
    );
} 